<?php

namespace app\modules\search\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\clinical\models\GeneInfo;

class SearchGene extends GeneInfo
{
	public $pt_name;
	public $ppt_id;

    public function rules()
    {
        // 只有在 rules() 函数中声明的字段才可以搜索
        return [
            [['isSent', 'pt_recheck', 'ck_comp'], 'integer'],
            [['ck_time', 'rp_time', 'recheck_time', 'disc_time', 'crt_time'], 'safe'],
            [['pt_name', 'ppt_id', 'charge_name', 'ck_program'], 'string', 'max' => 30],
            [['ck_result', 'disc_result', 'crt_name'], 'string', 'max' => 255],
        ];
    }

    public function search($params)
    {
        $query = GeneInfo::find()->where(['gene_info.delete_at' => 0])->with('patient');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'crt_time' => SORT_DESC,
                ]
            ],
        ]);

        // 从参数的数据中加载过滤条件，并验证
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }
        if($this->ppt_id || $this->pt_name){
            $query->joinWith(['patient']);
        }
        $this->clearDate(['crt_time', 'disc_time', 'recheck_time', 'rp_time', 'ck_time']);

        // 增加过滤条件来调整查询对象
        $query->andFilterWhere(['like', 'hspt_patient.pt_id', $this->ppt_id])
              ->andFilterWhere(['like', 'hspt_patient.pt_name', $this->pt_name])
              ->andFilterWhere(['isSent' => $this->isSent])
              ->andFilterWhere(['pt_recheck' => $this->pt_recheck])
              ->andFilterWhere(['ck_comp' => $this->ck_comp])
              ->andFilterWhere(['like', 'ck_time', $this->ck_time])
              ->andFilterWhere(['like', 'rp_time', $this->rp_time])
              ->andFilterWhere(['like', 'recheck_time', $this->recheck_time])
              ->andFilterWhere(['like', 'disc_time', $this->disc_time])
              ->andFilterWhere(['=', 'crt_name', $this->crt_name])
              ->andFilterWhere(['like', 'crt_time', $this->crt_time])
              ->andFilterWhere(['like', 'charge_name', $this->charge_name])
              ->andFilterWhere(['like', 'ck_program', $this->ck_program]);

        return $dataProvider;
    }

    protected function clearDate($arr)
    {
        foreach ($arr as $param) {
            $this->$param = preg_replace('/_*(-|:)_*(-|:)_*/', '', $this->$param);
        }
    }
}